<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片表格区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleClick"> 添加角色 </el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', index === 0 ? 'bdtop' : '', 'vCenter']"
              v-for="(item1, index) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染左侧的一级权限 -->
              <el-col :span="5">
                <el-tag
                  size="mini"
                  closable
                  @close="threeLevelClose(scope.row, item1.id)"
                >
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级跟三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[index2 === 0 ? '' : 'bdtop', 'vCenter']"
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      size="mini"
                      closable
                      @close="threeLevelClose(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      size="mini"
                      type="warning"
                      v-for="(item3, index3) in item2.children"
                      :key="item3.id"
                      :index="index3"
                      v-if="threeTagVisible"
                      closable
                      @close="threeLevelClose(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>  
                  {{ scope.row }}
                </pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editClick(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteClick(scope.row.id)"
              ref="treeRef"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-seach"
              @click="allocationLevelClick(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="allocationVisible"
      @close="allocationClose"
      width="40%"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        ref="treeRef"
        default-expand-all
        :default-checked-keys="defaultCheckedKeys"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="allocationVisible = false">取 消</el-button>
        <el-button type="primary" @click="allocationSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import {
  roleUserListApi,
  deletRoleRightsApi,
  rightsUserListApi,
  roleRightsApi
} from '../../request/api'
export default {
  data() {
    return {
      roleList: [], //存放角色列表的数组
      threeTagVisible: true,
      allocationVisible: false, //分配权限对话框boolean
      rightsList: [], //所有权限的数据
      treeProps:{//树形控件绑定对象
        label:'authName',
        children:'children'
      },
      defaultCheckedKeys:[],//默认选中节点的key数组
      roleId:'',//即将分配的角色id
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取角色列表
    getRoleList() {
      roleUserListApi().then(({ data: res }) => {
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.roleList = res.data
      })
    },
    //绑定点击编辑按钮事件
    editClick(id) {
      this.$message.success(
        '别看了，为了跑赢耶稣我决定舍弃了这个功能，想要写的可以参考上面的用户列表编辑功能'
      )
    },
    //绑定删除功能
    deleteClick(id) {
      this.$message.success('抱歉，这个我也舍弃了，大同小异呢！')
    },
    //绑定添加按钮
    addRoleClick() {
      this.$message.success('此功能未开发')
    },
    // 绑定删除权限权限按钮
    threeLevelClose(role, rightId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        //点击确定的回调
        .then(() => {
          deletRoleRightsApi(role.id, rightId).then(({ data: res }) => {
            if (res.meta.status !== 200) {
              return this.$message({
                type: 'error',
                message: res.meta.msg,
              })
            }
            role.children = res.data
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
          })
        })
        //点击取消的回调
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    //点击分配权限按钮  绑定分配权限
    allocationLevelClick(role) {
      rightsUserListApi('tree').then(({ data: res }) => {
        console.log(res)
        this.roleId = role.id
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.rightsList = res.data
        //获取到所有节点的id放置到defaultCheckedKeys数组中
        this.getLeafKeys(role,this.defaultCheckedKeys)
        this.allocationVisible = true
      })
    },
    // 分配权限对话框关闭按钮
    allocationClose() {
      this.defaultCheckedKeys = []
      console.log('关闭')
    },
    //分配权限对话框确定按钮  点击分配权限
    allocationSubmit() {
      const keyArr = [...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()]
      console.log(keyArr.join(","))
      const keyStr = keyArr.join(',')
      roleRightsApi(this.roleId,keyStr).then(({data:res}) => {
        if( res.meta.status !== 200 ){
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getRoleList()  //刷新列表
        this.allocationVisible = false
        
      })

    },
    //通过递归的形式，获取角色下所有三级权限的id,并保存到 defaultCheckedKeys 数组中
    getLeafKeys(node,arr){
      //如果当前node节点不包含children属性，则是三级节点
      if( !node.children ){
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys( item, arr ))
    }
  },
}
</script>

<style lang="scss" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vCenter {
  display: flex;
  align-items: center;
}
.el-dialog__footer{
  position: sticky!important;
  bottom: 0px!important;
  right: 0px!important;
}
</style>